import storge from 'good-storage'

const SEARCH_KEY = '__search__'
const SEARCH_MAX_LENGTH = 15

const PLAY_KEY = '__play__'
const PLAY_MAX_LENGTH = 200

const FAVORITE_KEY = '__favorite__'
const FAVORITE_MAX_LENGTH = 200

// 往数组插入一个值
function insertArray(arr, query, compare, maxLen) {
  const index = arr.findIndex(compare)
  if(index === 0) {
    return
  }
  if(index > 0) {
    arr.splice(index, 1)
  }
  arr.unshift(query)
  if(maxLen && maxLen < arr.length) {
    arr.pop()
  }
}

// 往数组删除一个值
function deleteFromArray(arr, compare) {
  let index = arr.findIndex(compare)
  if(index > -1) {
    arr.splice(index, 1)
  }
}

// 保存搜索历史到localStorge中
export function saveSearch(query) {
  // 默认是个空数组
  let searches = storge.get(SEARCH_KEY, [])
  insertArray(searches, query, (item) => {
    return item === query
  }, SEARCH_MAX_LENGTH)
  storge.set(SEARCH_KEY, searches)
  return searches
}

// 从本地获取搜索历史数据
export function loadSearch() {
  return storge.get(SEARCH_KEY, [])
}


// 删除某条历史
export function deleteSearch(query) {
  let searches = storge.get(SEARCH_KEY, [])
  deleteFromArray(searches, (item) => {
    return item === query
  })
  storge.set(SEARCH_KEY, searches)
  return searches
}

// 清空历史
export function clearSearch() {
  storge.remove(SEARCH_KEY)
  return []
}

// 保存播放歌曲历史
export function savePlay(song) {
  let songs = storge.get(PLAY_KEY, [])
  insertArray(songs, song, (item) => {
    return song.id === item.id
  }, PLAY_MAX_LENGTH)
  storge.set(PLAY_KEY, songs)
  return songs
}

// 加载播放歌曲历史
export function loadPlay() {
  return storge.get(PLAY_KEY, [])
}

// 保存收藏列表
export function saveFavorite(song) {
  let list = storge.get(FAVORITE_KEY, [])
  insertArray(list, song, (item) => {
    return item.id === song.id
  }, FAVORITE_MAX_LENGTH)
  storge.set(FAVORITE_KEY, list)
  return list
}

// 删除收藏列表
export function deleteFavorite(song) {
  let list = storge.get(FAVORITE_KEY, [])
  deleteFromArray(list, (item) => {
    return item.id === song.id
  })
  storge.set(FAVORITE_KEY, list)
  return list
}

// 加载收藏列表
export function loadFavorite() {
  return storge.get(FAVORITE_KEY, [])
}